package com.weme.common.view

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.AspectRatioFrameLayout
import com.weme.common.databinding.ViewPlayVideoBinding

@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class)
class PlayVideoView  @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0) : FrameLayout(context, attributeSet, defStyle) {
    private val viewBinding = ViewPlayVideoBinding.inflate(LayoutInflater.from(context), this, true)
    val player = ExoPlayer.Builder(context).build()

    init {
        viewBinding.playerView.player = player
        player.repeatMode = Player.REPEAT_MODE_ONE
        //填充媒体数据


        // 设置拉伸方式为 ResizeMode.ZOOM
        viewBinding.playerView.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM

    }


    fun setPlayUrl(url:String,listener: Player.Listener){
        player.addMediaItem(MediaItem.fromUri(url))
        //准备播放
        player.prepare()

        player.addListener(listener)

        // 开始播放
        player.playWhenReady = true
    }
    fun stopPlay(){
        player.playWhenReady = false
        viewBinding.playerView.player?.release()
    }

}